<template>
  <el-row class="mt-8px" :gutter="8" justify="space-between">
    <el-col :xl="16" :lg="16" :md="24" :sm="24" :xs="24" class="mb-8px">
      <el-card shadow="never">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>监控面板</span>
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <el-row>
            <el-col
              v-for="(item, index) in projects"
              :key="`card-${index}`"
              :xl="8"
              :lg="8"
              :md="8"
              :sm="24"
              :xs="24"
            >
              <el-card shadow="hover" class="mr-5px mt-5px">
                <div class="flex items-center justify-between">
                  <p class="text-12px">名称：{{ item.plotName }}</p>
                  <p class="text-12px">位置：{{ item.location }}</p>
                </div>
                <div class="mt-8px flex items-center justify-between">
                  <p class="text-12px">面积：{{ item.area }}</p>
                  <p class="text-12px">土壤类型：{{ item.soilType }}</p>
                </div>
                <div class="mt-8px flex items-center justify-between">
                  <p class="text-12px">作物名称：{{ item.crop.name }}</p>
                  <p class="text-12px">种植时间：{{ item.crop.plantDate }}</p>
                </div>
                <div class="mt-8px flex items-center justify-between">
                  <p class="text-12px">🌡️ 土壤温度：{{ item.soil_temperature }}</p>
                  <p class="text-12px">💧 土壤湿度：{{ item.soil_humidity }}</p>
                </div>
                <div class="mt-8px flex items-center justify-between">
                  <p class="text-12px">管理负责人：{{ item.manager.name }}</p>
                  <p class="text-12px">联系方式：{{ item.manager.phone }}</p>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-skeleton>
      </el-card>

      <el-card shadow="never" class="mt-8px">
        <el-skeleton :loading="loading" animated>
          <el-row :gutter="20" justify="space-between">
            <el-col :xl="10" :lg="10" :md="24" :sm="24" :xs="24">
              <el-card shadow="hover" class="mb-8px">
                <el-skeleton :loading="loading" animated>
                  <Echart :options="pieOptionsData" :height="280" />
                </el-skeleton>
              </el-card>
            </el-col>
            <el-col :xl="14" :lg="14" :md="24" :sm="24" :xs="24">
              <el-card shadow="hover" class="mb-8px">
                <el-skeleton :loading="loading" animated>
                  <Echart :options="barOptionsData" :height="280" />
                </el-skeleton>
              </el-card>
            </el-col>
          </el-row>
        </el-skeleton>
      </el-card>
    </el-col>
    <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24" class="mb-8px">
      <el-card shadow="never">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>待办事务</span>
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <el-col v-for="item in shortcut" :key="`team-${item.name}`">
            <div style="border: 1px solid #ebeef5; padding: 10px; border-radius: 3px">
              <div shadow="hover" class="mt-8px flex items-center justify-between">
                <p class="text-12px"
                  >{{ item.createdAt }} {{ item.plotName }}{{ item.taskType }}
                </p>
                <p class="text-12px"
                  >优先级：<span :style="{ color: item.color }">{{ item.priority }}</span></p
                >
              </div>
              <div class="mt-8px flex items-center justify-between">
                <p class="text-12px">任务描述：{{ item.description }} </p>
                <p class="text-12px"
                  >状态：<span>{{ item.status }}</span></p
                >
              </div>
            </div>
          </el-col>
        </el-skeleton>
      </el-card>
      <el-card shadow="never" class="mt-8px">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>告警管理</span>
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <div v-for="(item, index) in notice" :key="`dynamics-${index}`">
            <div class="flex items-center">
              <img
                src="@/assets/imgs/alarm_o.png"
                alt=""
                class="mr-25px w-50px"
                v-if="item.alertLevel == '中'"
              />
              <img
                src="@/assets/imgs/alarm_r.png"
                alt=""
                class="mr-25px w-50px"
                v-else-if="item.alertLevel == '高'"
              />
              <img src="@/assets/imgs/alarm_g.png" alt="" class="mr-25px w-50px" v-else />
              <div>
                <div class="flex items-center justify-between">
                  <p class="text-14px">名称：{{ item.plotName }} </p>
                  <p class="text-14px"
                    >告警类型：<span style="color: #36b8cd" class="text-14px">{{
                      item.alertType
                    }}</span></p
                  >
                </div>
                <div class="flex items-center justify-between">
                  <p class="text-14px">告警详情：{{ item.description }} </p>
                </div>
                <div class="flex items-center justify-between">
                  <p class="text-14px">告警时间：{{ item.timestamp }} </p>
                  <p class="text-14px"
                    >状态：<span>{{ item.status }}</span></p
                  >
                </div>
                <!-- <div class="text-14px"> {{ item.alertType }} : {{ item.title }} </div>
                <div class="mt-16px text-12px text-gray-400">
                  {{ formatTime(item.date, 'yyyy-MM-dd') }}
                </div> -->
              </div>
            </div>
            <el-divider />
          </div>
        </el-skeleton>
      </el-card>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import { set } from 'lodash-es'
import { EChartsOption } from 'echarts'
import { formatTime } from '@/utils'

import { useUserStore } from '@/store/modules/user'
import { useWatermark } from '@/hooks/web/useWatermark'
import type { WorkplaceTotal, Project, Notice, Shortcut } from './types'
import { pieOptions, barOptions } from './echarts-data'

defineOptions({ name: 'Home' })

const { t } = useI18n()
const userStore = useUserStore()
const { setWatermark } = useWatermark()
const loading = ref(true)
const avatar = userStore.getUser.avatar
const username = userStore.getUser.nickname
const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption
// 获取统计数
let totalSate = reactive<WorkplaceTotal>({
  project: 0,
  access: 0,
  todo: 0
})

const getCount = async () => {
  const data = {
    project: 40,
    access: 2340,
    todo: 10
  }
  totalSate = Object.assign(totalSate, data)
}

// 获取项目数
let projects = reactive<Project[]>([])
const getProject = async () => {
  const data = [
    {
      plotId: 'A01-001',
      plotName: '试验田一区',
      location: '天津市西青区X村',
      area: '2.5亩',
      soilType: '水稻土',
      crop: {
        name: '水稻（华粳9号）',
        plantDate: '2025-03-01'
      },
      manager: {
        name: '孙超',
        phone: '13912345678'
      },
      soil_temperature: '18.6°C',
      soil_humidity: '32.5%'
    },
    {
      plotId: 'A01-002',
      plotName: '试验田二区',
      location: '天津市西青区X村',
      area: '2.5亩',
      soilType: '棕壤',
      crop: {
        name: '小麦',
        plantDate: '2025-03-06'
      },
      manager: {
        name: '张超',
        phone: '13912345678'
      },
      soil_temperature: '18.6°C',
      soil_humidity: '32.5%'
    },
    {
      plotId: 'A01-003',
      plotName: '试验田三区',
      location: '天津市西青区X村',
      area: '2.5亩',
      soilType: '黑土',
      crop: {
        name: '玉米',
        plantDate: '2025-03-21'
      },
      manager: {
        name: '刘晨',
        phone: '13912345678'
      },
      soil_temperature: '18.6°C',
      soil_humidity: '32.5%'
    },
    {
      plotId: 'A01-004',
      plotName: '试验田四区',
      location: '天津市西青区X村',
      area: '2.5亩',
      soilType: '砂土',
      crop: {
        name: '花生',
        plantDate: '2025-04-01'
      },
      manager: {
        name: '王小东',
        phone: '13912345678'
      },
      soil_temperature: '18.6°C',
      soil_humidity: '32.5%'
    },
    {
      plotId: 'A01-005',
      plotName: '试验田五区',
      location: '天津市西青区X村',
      area: '2.5亩',
      soilType: '黏壤土',
      crop: {
        name: '水稻（华粳9号）',
        plantDate: '2025-04-11'
      },
      manager: {
        name: '李四',
        phone: '13912345678'
      },
      soil_temperature: '18.6°C',
      soil_humidity: '32.5%'
    },
    {
      plotId: 'A01-006',
      plotName: '试验田六区',
      location: '天津市西青区X村',
      area: '2.5亩',
      soilType: '黏壤土',
      crop: {
        name: '水稻（华粳9号）',
        plantDate: '2025-04-01'
      },
      manager: {
        name: '赵东',
        phone: '13912345678'
      },
      soil_temperature: '18.6°C',
      soil_humidity: '32.5%'
    }
  ]
  projects = Object.assign(projects, data)
}

// 获取告警管理
let notice = reactive<Notice[]>([])
const getNotice = async () => {
  const data = [
    {
      alertId: 'ALERT-20250415001',
      plotName: '东试验田一区',
      alertType: '土壤湿度异常',
      alertLevel: '高',
      status: '未处理',
      timestamp: '2025-04-15 08:20',
      deviceId: 'SENSOR-T001',
      alertValue: '湿度 17%（低于阈值 25%）',
      description: '检测到连续两小时湿度偏低，可能存在干旱风险。',
      handler: ''
    },
    {
      alertId: 'ALERT-20250415002',
      plotName: '西试验田二号',
      alertType: '设备离线',
      alertLevel: '中',
      status: '处理中',
      timestamp: '2025-04-14 21:45',
      deviceId: 'CAM-002',
      alertValue: '设备 12 小时未上传数据',
      description: '西侧摄像头已断联，请检查设备电源或信号。',
      handler: '李强'
    },
    // {
    //   alertId: 'ALERT-20250415003',
    //   plotName: '北试验田五号',
    //   alertType: '气温异常升高',
    //   alertLevel: '高',
    //   status: '未处理',
    //   timestamp: '2025-04-15 11:30',
    //   deviceId: 'SENSOR-TEMP005',
    //   alertValue: '当前温度 39.2°C',
    //   description: '温度超过阈值 35°C，需检查作物抗热情况。',
    //   handler: ''
    // },
    {
      alertId: 'ALERT-20250415004',
      plotName: '南试验田三区',
      alertType: '采样延误',
      alertLevel: '低',
      status: '已处理',
      timestamp: '2025-04-13 16:00',
      deviceId: '',
      alertValue: '任务超期未完成',
      description: '土壤采样任务已超过计划时间 2 天，请补采。',
      handler: '赵敏'
    }
    // {
    //   alertId: 'ALERT-20250415005',
    //   plotName: '东试验田一区',
    //   alertType: '视频监控异常',
    //   alertLevel: '中',
    //   status: '处理中',
    //   timestamp: '2025-04-15 10:10',
    //   deviceId: 'CAM-001',
    //   alertValue: '画面静止/卡顿',
    //   description: '监控画面静止超过 5 分钟，怀疑图像采集模块异常。',
    //   handler: '张强'
    // }
  ]
  notice = Object.assign(notice, data)
}

// 获取快捷入口
let shortcut = reactive<Shortcut[]>([])

const getShortcut = async () => {
  const data = [
    {
      taskId: 'TODO-20250415001',
      plotName: '东试验田一区',
      taskType: '土壤采样',
      priority: '高',
      color: 'red',
      status: '待处理',
      deadline: '2025-04-16',
      createdAt: '2025-04-15 08:30',
      assignedBy: '管理员张强',
      executor: '李明',
      description: '检测地块湿度下降，需采集土壤样品检测含水量。'
    },
    {
      taskId: 'TODO-20250415002',
      plotName: '西试验田二号',
      taskType: '作物巡视',
      priority: '中',
      color: 'orange',
      status: '处理中',
      deadline: '2025-04-17',
      createdAt: '2025-04-14 14:10',
      assignedBy: '系统自动生成',
      executor: '王红',
      description: '定期巡视，记录作物叶片黄化情况，拍照上传。'
    },
    {
      taskId: 'TODO-20250415003',
      plotName: '南试验田三区',
      taskType: '灌溉控制',
      priority: '高',
      color: 'red',
      status: '已完成',
      deadline: '2025-04-15',
      createdAt: '2025-04-15 07:00',
      assignedBy: '系统自动生成',
      executor: '赵强',
      description: '地块湿度<25%，已完成自动灌溉并记录反馈。'
    },
    {
      taskId: 'TODO-20250415004',
      plotName: '东试验田一区',
      taskType: '设备维护',
      priority: '低',
      color: 'green',
      status: '待处理',
      deadline: '2025-04-20',
      createdAt: '2025-04-13 11:45',
      assignedBy: '管理员张强',
      executor: '刘波',
      description: '湿度传感器电池电量低，需更换电池并检查上传频率。'
    }
    // {
    //   taskId: 'TODO-20250415005',
    //   plotName: '北试验田五号',
    //   taskType: '样品检测',
    //   priority: '中',
    //   color: 'orange',
    //   status: '待处理',
    //   deadline: '2025-04-18',
    //   createdAt: '2025-04-15 09:20',
    //   assignedBy: '管理员赵云',
    //   executor: '孙倩',
    //   description: '已采集样品编号 SP-20250415001，请完成养分含量检测。'
    // }
  ]
  shortcut = Object.assign(shortcut, data)
}

// 用户来源
const getUserAccessSource = async () => {
  const data = [
    { value: 5, name: 'analysis.monday' },
    { value: 8, name: 'analysis.tuesday' },
    { value: 12, name: 'analysis.wednesday' },
    { value: 14, name: 'analysis.thursday' },
    { value: 6, name: 'analysis.friday' },
    { value: 3, name: 'analysis.saturday' },
    { value: 8, name: 'analysis.sunday' }
  ]
  set(
    pieOptionsData,
    'legend.data',
    data.map((v) => t(v.name))
  )
  pieOptionsData!.series![0].data = data.map((v) => {
    return {
      name: t(v.name),
      value: v.value
    }
  })
}
const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption

// 周活跃量
const getWeeklyUserActivity = async () => {
  const data = [
    { value: 5, name: 'analysis.monday' },
    { value: 8, name: 'analysis.tuesday' },
    { value: 12, name: 'analysis.wednesday' },
    { value: 14, name: 'analysis.thursday' },
    { value: 6, name: 'analysis.friday' },
    { value: 3, name: 'analysis.saturday' },
    { value: 8, name: 'analysis.sunday' }
  ]
  set(
    barOptionsData,
    'xAxis.data',
    data.map((v) => t(v.name))
  )
  set(barOptionsData, 'series', [
    {
      name: '告警数量',
      data: data.map((v) => v.value),
      type: 'bar'
    }
  ])
}

const getAllApi = async () => {
  await Promise.all([
    getCount(),
    getProject(),
    getNotice(),
    getShortcut(),
    getUserAccessSource(),
    getWeeklyUserActivity()
  ])
  loading.value = false
}

getAllApi()
</script>
